"use client";

import React, { useState, useRef, useEffect } from "react";
import {
  Send,
  Users,
  MessageCircle,
  Settings,
  Edit3,
  ArrowLeft,
  Copy,
  ExternalLink,
} from "lucide-react";
import { useTokenChat } from "../hooks/useTokenChat";
import { Token } from "../types/api";
import { ChatUser, ChatMessage } from "../types/chat";
import { toast } from "react-hot-toast";
import Image from "next/image";
import { formatPrice, formatMarketCap } from "../utils/formatters";

interface TokenChatRoomProps {
  token: Token | null;
  onClose: () => void;
}

export function TokenChatRoom({ token, onClose }: TokenChatRoomProps) {
  const {
    connected,
    connecting,
    error,
    messages,
    users,
    currentUser,
    sendMessage,
    changeUsername,
  } = useTokenChat(token?.mint);

  const [messageInput, setMessageInput] = useState("");
  const [showSettings, setShowSettings] = useState(false);
  const [usernameInput, setUsernameInput] = useState(currentUser || "");
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  // 自动滚动到最新消息
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  // 当聊天室打开时聚焦输入框
  useEffect(() => {
    if (token && connected) {
      setTimeout(() => inputRef.current?.focus(), 100);
    }
  }, [token, connected]);

  const handleSendMessage = () => {
    if (messageInput.trim() && connected) {
      sendMessage(messageInput);
      setMessageInput("");
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  const handleUsernameChange = () => {
    if (usernameInput.trim() && usernameInput !== currentUser) {
      changeUsername(usernameInput.trim());
      setShowSettings(false);
      toast.success("用户名已更新");
    }
  };

  const formatTime = (timestamp: string) => {
    const date = new Date(timestamp);
    return date.toLocaleTimeString("zh-CN", {
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    toast.success("已复制到剪贴板");
  };

  // 检测token类型并生成相应的区块链浏览器链接
  const getExplorerLink = (token: Token) => {
    // 如果token有明确的chain字段，使用它
    if ('chain' in token && token.chain === 'xlayer') {
      return `https://www.oklink.com/x-layer-testnet/address/${token.mint}`;
    }
    
    // 通过mint/tokenAddress格式来判断链类型
    // Solana地址通常是44个字符的base58编码
    // 以太坊地址是42个字符（包括0x前缀）
    if (token.mint.startsWith('0x') && token.mint.length === 42) {
      // 以太坊格式地址，可能是XLayer
      return `https://www.oklink.com/x-layer-testnet/address/${token.mint}`;
    } else {
      // 默认使用Solana浏览器
      return `https://solscan.io/token/${token.mint}`;
    }
  };

  if (!token) {
    return null;
  }

  return (
    <div className="fixed inset-0 z-50 bg-gray-900 text-white">
      <div className="h-full flex flex-col">
        {/* Header */}
        <div className="border-b border-gray-700 bg-gray-800">
          <div className="app-container">
            <div className="flex items-center justify-between py-4">
              <div className="flex items-center gap-3">
                <button
                  onClick={onClose}
                  className="text-gray-400 hover:text-white transition-colors"
                  title="返回"
                >
                  <ArrowLeft size={20} />
                </button>
                
                {/* Token Info */}
                <div className="flex items-center gap-3">
                  {token.image ? (
                    <Image
                      src={token.image}
                      alt={token.name}
                      width={32}
                      height={32}
                      className="rounded-full object-cover"
                    />
                  ) : (
                    <div className="w-8 h-8 bg-gradient-to-br from-purple-500 to-indigo-600 rounded-full flex items-center justify-center">
                      <span className="text-white font-bold text-sm">
                        {token.symbol.charAt(0)}
                      </span>
                    </div>
                  )}
                  <div>
                    <div className="flex items-center gap-2">
                      <h2 className="text-lg font-bold">{token.name}</h2>
                      {token.isGraduated && (
                        <span className="inline-flex items-center px-2 py-1 text-xs font-medium bg-yellow-400 text-black border border-black rounded">
                          🎓 已毕业
                        </span>
                      )}
                    </div>
                    <p className="text-sm text-gray-400">{token.symbol}</p>
                  </div>
                </div>
                
                {connected && (
                  <span className="flex items-center gap-1 text-sm text-green-400">
                    <div className="w-2 h-2 bg-green-400 rounded-full"></div>
                    online
                  </span>
                )}
              </div>
              
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setShowSettings(!showSettings)}
                  className="text-gray-400 hover:text-white transition-colors"
                  title="Settings"
                >
                  <Settings size={20} />
                </button>
              </div>
            </div>
          </div>
        </div>

        {/* Token Details Panel */}
        <div className="bg-gray-800 border-b border-gray-700">
          <div className="app-container py-4">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
              <div className="text-center">
                <div className="text-gray-400">price</div>
                <div className="font-semibold">{formatPrice(token.price)}</div>
              </div>
              <div className="text-center">
                <div className="text-gray-400">TVL</div>
                <div className="font-semibold">
                  {formatMarketCap(token.marketCap)}
                </div>
              </div>
              <div className="text-center">
                <div className="text-gray-400">Holders</div>
                <div className="font-semibold">
                  {token.holders.toLocaleString()}
                </div>
              </div>
              <div className="text-center">
                <div className="text-gray-400">address</div>
                <div className="flex items-center gap-1 justify-center">
                  <span className="font-mono text-xs">
                    {`${token.mint.slice(0, 4)}...${token.mint.slice(-4)}`}
                  </span>
                  <button
                    onClick={() => copyToClipboard(token.mint)}
                    className="text-gray-400 hover:text-white"
                  >
                    <Copy size={12} />
                  </button>
                  <a
                    href={getExplorerLink(token)}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-gray-400 hover:text-white"
                  >
                    <ExternalLink size={12} />
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Settings Panel */}
        {showSettings && (
          <div className="bg-gray-800 border-b border-gray-700">
            <div className="app-container py-4">
              <div className="space-y-3">
                <div>
                  <label className="block text-sm font-medium text-gray-300 mb-1">
                    username
                  </label>
                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={usernameInput}
                      onChange={(e) => setUsernameInput(e.target.value)}
                      className="flex-1 bg-gray-700 border border-gray-600 rounded px-3 py-2 text-sm text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-purple-500"
                      placeholder="Enter username"
                      maxLength={20}
                    />
                    <button
                      onClick={handleUsernameChange}
                      className="bg-purple-600 hover:bg-purple-700 text-white px-3 py-2 rounded text-sm transition-colors"
                    >
                      <Edit3 size={16} />
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Connection Status */}
        {!connected && (
          <div className="bg-yellow-900 border-b border-yellow-700">
            <div className="app-container py-4">
              <div className="flex items-center gap-2 text-yellow-300">
                <div className="w-2 h-2 bg-yellow-400 rounded-full animate-pulse"></div>
                <span className="text-sm">
                  {connecting
                    ? "Connecting..."
                    : error
                    ? `Connection failed: ${error}`
                    : "Not connected"}
                </span>
              </div>
            </div>
          </div>
        )}

        {/* Online Users */}
        <div className="bg-gray-800 border-b border-gray-700">
          <div className="app-container py-4">
            <div className="flex items-center gap-2 mb-2">
              <Users size={16} />
              <span className="text-sm font-medium">Online users ({users.length})</span>
            </div>
            <div className="flex flex-wrap gap-1">
              {users.map((user: ChatUser) => (
                <span
                  key={user.id}
                  className={`text-xs px-2 py-1 rounded-full ${
                    user.username === currentUser
                      ? "bg-purple-600 text-white"
                      : "bg-gray-700 text-gray-300"
                  }`}
                >
                  {user.username}
                </span>
              ))}
            </div>
          </div>
        </div>

        {/* Messages */}
        <div className="flex-1 overflow-y-auto">
          <div className="app-container py-5">
            {messages.length === 0 ? (
              <div className="text-center text-gray-500 mt-8">
                <MessageCircle size={48} className="mx-auto mb-2 opacity-50" />
                <p>Welcome to {token.name} chat room!</p>
                <p className="text-sm">Here you can chat with {token.symbol} community members</p>
                <p className="text-sm">Send your first message to start chatting!</p>
              </div>
            ) : (
              <div className="flex flex-col gap-5">
                {messages.map((message: ChatMessage) => {
                  const isSelf = message.username === currentUser;
                  if (message.isSystem) {
                    return (
                      <div key={message.id} className="flex justify-center">
                        <div className="px-4 py-1 text-xs bg-gray-800/60 text-gray-400 rounded-full italic tracking-wide">
                          {message.message}
                        </div>
                      </div>
                    );
                  }
                  return (
                    <div
                      key={message.id}
                      className={`flex ${isSelf ? 'justify-end' : 'justify-start'} px-1`}
                    >
                      <div
                        className={`relative max-w-[85%] md:max-w-[70%] px-4 py-2 rounded-2xl shadow-sm leading-relaxed break-words whitespace-pre-wrap text-sm border border-transparent ${
                          isSelf
                            ? 'bg-gradient-to-br from-purple-600 to-purple-500 text-white rounded-tr-sm'
                            : 'bg-gray-700 text-gray-100 rounded-tl-sm'
                        }`}
                      >
                        <div className="flex items-center gap-2 mb-1">
                          <span className="text-xs font-medium opacity-80">{message.username}</span>
                          <span className="text-[10px] opacity-50">{formatTime(message.timestamp)}</span>
                        </div>
                        {message.message}
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
            <div ref={messagesEndRef} />
          </div>
        </div>

        {/* Message Input */}
        <div className="border-t border-gray-700 bg-gray-900">
          <div className="app-container py-4">
            <div className="flex gap-2">
              <input
                ref={inputRef}
                type="text"
                value={messageInput}
                onChange={(e) => setMessageInput(e.target.value)}
                onKeyPress={handleKeyPress}
                disabled={!connected}
                className="flex-1 bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-purple-500 disabled:opacity-50"
                placeholder={
                  connected ? `Chat in ${token.symbol} chat room...` : "Connecting..."
                }
                maxLength={500}
              />
              <button
                onClick={handleSendMessage}
                disabled={!connected || !messageInput.trim()}
                className="bg-purple-600 hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed text-white p-2 rounded-lg transition-colors"
              >
                <Send size={20} />
              </button>
            </div>
            {messageInput.length > 0 && (
              <div className="text-xs text-gray-500 mt-1 text-right">
                {messageInput.length}/500
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
